﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using UCNKompetenceBors.Database;
using UCNKompetenceBors.Model;

namespace UCNKompetenceBors.Admin
{
    public partial class adminExchangeCategory : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                this.Form.DefaultButton = btnAddCategory.UniqueID;

                BindSubMenu();
                BindData();
            }

            #region Globalization
            string culture = String.Empty;

            if (HttpContext.Current.Session["MyCulture"] != null)
                culture = HttpContext.Current.Session["MyCulture"].ToString();

            if (!String.IsNullOrEmpty(culture))
                GeneralTools.SetCulture(culture);

            LocalizeControls();
            #endregion
        }

        /// <summary>
        /// Binds the sub menu links.
        /// </summary>
        private void BindSubMenu()
        {
            hyLinkAdminDashboard.NavigateUrl = "~/Admin/admin.aspx";
            hyLinkUserHandling.NavigateUrl = "~/Admin/adminUsers.aspx";
            hyLinkNewsHandling.NavigateUrl = "~/Admin/adminNews.aspx";
            hyLinkAdminExchange.NavigateUrl = "~/Admin/adminExchange.aspx";
            hyLinkAdminSale.NavigateUrl = "~/Admin/adminExchangeSale.aspx";
            hyLinkAdminPurchase.NavigateUrl = "~/Admin/adminExchangePurchase.aspx";
            hyLinkAdminCategory.NavigateUrl = "~/Admin/adminExchangeCategory.aspx";
            hyLinkEditInformation.NavigateUrl = "~/Admin/adminInformation.aspx";
            hyLinkContactPerson.NavigateUrl = "~/Admin/adminContactPerson.aspx";
            hylinkDepartment.NavigateUrl = "~/Admin/adminDepartment.aspx";
            hyLinkResetUsers.NavigateUrl = "~/Admin/adminUsersReset.aspx";
        }

        /// <summary>
        /// Binds the GridView with categories.
        /// </summary>
        private void BindData()
        {
            List<Category> categories = new List<Category>();
            string culture = String.Empty;

            if (HttpContext.Current.Session["MyCulture"] != null)
                culture = HttpContext.Current.Session["MyCulture"].ToString();

            categories = dbAdmin.GetAllCategories();

            gvAdminCategory.DataSource = categories;
            gvAdminCategory.DataBind();
        }

        /// <summary>
        /// Updates a row, based on the input parameters.
        /// </summary>
        /// <param name="categoryId">Specifies the ID of the category to be updated.</param>
        /// <param name="categoryName">Specifies the new name of the category to be updated.</param>
        /// <param name="localizedCategoryName">Specifies the new localized name of the category to be updated.</param>
        private void UpdateRow(int categoryId, string categoryName, string localizedCategoryName)
        {
            dbAdmin.UpdateCategory(categoryId, categoryName, localizedCategoryName);
        }

        /// <summary>
        /// Deletes a row, based on the categoryId input parameter.
        /// </summary>
        /// <param name="categoryId">Specifies the ID of the category to be deleted.</param>
        private void DeleteRow(int categoryId)
        {
            dbAdmin.DeleteCategory(categoryId);
        }

        /// <summary>
        /// Inserts a category, based on the input parameters.
        /// </summary>
        /// <param name="categoryName">Specifies the name of the category to be inserted.</param>
        /// <param name="localizedCategoryName">Specifies the localized name of the category to be inserted.</param>
        private void InsertCategory(string categoryName, string localizedCategoryName)
        {
            dbAdmin.CreateCategory(categoryName, localizedCategoryName);
        }

        /// <summary>
        /// Clears the textbox controls.
        /// </summary>
        private void ClearControls()
        {
            txtAddLocalizedCategory.Text = "";
            txtAddCategory.Text = "";
        }

        /// <summary>
        /// Validates a category name, based on the categoryName input parameter.
        /// </summary>
        /// <param name="categoryName">Specifies the category name to be validated.</param>
        /// <returns>Returns a boolean specifying whether or not the category name already exists.</returns>
        private bool ValidateCategoryName(string categoryName)
        {
            return dbAdmin.ValidateCategoryName(categoryName);
        }

        /// <summary>
        /// Validates a localized category name, based on the localizedCategoryName input parameter.
        /// </summary>
        /// <param name="localizedCategoryName">Specifies the localized category name to be validated.</param>
        /// <returns>Returns a bool specifying whether or not the localized category name already exists.</returns>
        private bool ValidateLocalizedCategoryName(string localizedCategoryName)
        {
            return dbAdmin.ValidateLocalizedCategoryName(localizedCategoryName);
        }

        /// <summary>
        /// Validates whether or not a category is in use by a sale or a purchase.
        /// </summary>
        /// <param name="categoryId">Specifies the ID of the category to be validated.</param>
        /// <returns>Returns a bool specifying whether or not the category is in use.</returns>
        private bool ValidateCategoryUsed(int categoryId)
        {
            return dbAdmin.ValidateCategoryUsed(categoryId);
        }

        //Event fired when the Edit button in the gridview is clicked
        protected void gvAdminCategory_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView gv = (GridView)sender;

            gv.EditIndex = e.NewEditIndex;

            BindData();
        }

        //Event fired when the Update button in the gridview is clicked
        protected void gvAdminCategory_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            GridView gv = (GridView)sender;

            int categoryID = 0;

            foreach (Label lbl in gv.Rows[e.RowIndex].Cells[2].Controls.OfType<Label>())
            {
                if (lbl.ID == "lblCategoryID")
                    categoryID = Convert.ToInt32(lbl.Text);
            }

            string categoryName = "";

            categoryName = e.NewValues["CategoryName"].ToString();

            string localizedCategoryName = "";

            localizedCategoryName = e.NewValues["LocalizedCategoryName"].ToString();

            if (!String.IsNullOrEmpty(categoryName) && categoryID != 0)
                UpdateRow(categoryID, categoryName, localizedCategoryName);

            gv.EditIndex = -1;

            BindData();
        }

        //Event fired when the Cancel button in the gridview is clicked
        protected void gvAdminCategory_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView gv = (GridView)sender;

            gv.EditIndex = -1;

            BindData();
        }

        //Event fired when the btnAddCategory button is clicked
        protected void btnAddCategory_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                string categoryName = txtAddCategory.Text;
                string localizedCategoryName = txtAddLocalizedCategory.Text;

                InsertCategory(categoryName, localizedCategoryName);

                ClearControls();
                BindData();
            }
        }

        //Event fired when the custom validator validates on the server
        protected void cusvalLocalizedCategoryName_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (ValidateLocalizedCategoryName(txtAddLocalizedCategory.Text))
            {
                args.IsValid = false;
            }
            else
            {
                args.IsValid = true;
            }
        }

        //Event fired when the custom validator validates on the server
        protected void cusvalCategoryName_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (ValidateCategoryName(txtAddCategory.Text))
            {
                args.IsValid = false;
            }
            else
            {
                args.IsValid = true;
            }
        }

        //Event fired when the Delete button in the gridview is clicked
        protected void gvAdminCategory_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int categoryId = 0;

            foreach (Label lbl in gvAdminCategory.Rows[e.RowIndex].Cells[2].Controls.OfType<Label>())
            {
                if (lbl.ID == "lblCategoryID")
                    categoryId = Convert.ToInt32(lbl.Text);
            }

            DeleteRow(categoryId);

            BindData();
        }

        //Event fired when the gridview is databound
        protected void gvAdminCategory_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string name = e.Row.Cells[0].Text;

                int categoryID = 0;

                foreach (Label lbl in e.Row.Cells[2].Controls.OfType<Label>())
                {
                    if (lbl.ID == "lblCategoryID")
                        categoryID = Convert.ToInt32(lbl.Text);
                }

                if (categoryID != 0)
                {
                    if (ValidateCategoryUsed(categoryID))
                    {
                        foreach (LinkButton button in e.Row.Cells[4].Controls.OfType<LinkButton>())
                        {
                            if (button.CommandName == "Delete")
                            {
                                button.Enabled = false;
                                button.ToolTip = "This category is being used by 1 or more items, deletion is impossible";
                                button.ForeColor = System.Drawing.Color.LightGray;
                            }
                        }
                    }
                    else
                    {
                        foreach (LinkButton button in e.Row.Cells[4].Controls.OfType<LinkButton>())
                        {
                            if (button.CommandName == "Delete")
                            {
                                button.Attributes["onclick"] = "if(!confirm('" + GetLocalResourceObject("ConfirmBoxText").ToString() + "\"" + name + "\"?')) { return false; };";
                            }
                        }
                    }   
                }
            }
        }

        /// <summary>
        /// Localizes the controls of the site, based on the current UI Culture.
        /// </summary>
        private void LocalizeControls()
        {
            hyLinkAdminDashboard.Text = GetLocalResourceObject("hyLinkAdminDashboardText").ToString();
            hyLinkUserHandling.Text = GetLocalResourceObject("hyLinkUserHandlingText").ToString();
            hyLinkAdminExchange.Text = GetLocalResourceObject("hyLinkAdminExchangeText").ToString();
            hyLinkNewsHandling.Text = GetLocalResourceObject("hyLinkNewsHandlingText").ToString();
            hyLinkEditInformation.Text = GetLocalResourceObject("hyLinkEditInformationText").ToString();
            hyLinkResetUsers.Text = GetLocalResourceObject("hyLinkResetUsersText").ToString();
            hylinkDepartment.Text = GetLocalResourceObject("hylinkDepartmentText").ToString();
            hyLinkContactPerson.Text = GetLocalResourceObject("hyLinkContactPersonsText").ToString();

            hyLinkAdminPurchase.Text = GetLocalResourceObject("hyLinkAdminPurchaseText").ToString();
            hyLinkAdminSale.Text = GetLocalResourceObject("hyLinkAdminSaleText").ToString();
            hyLinkAdminCategory.Text = GetLocalResourceObject("hyLinkAdminCategoryText").ToString();

            lblAddCategory.Text = GetLocalResourceObject("lblAddCategoryText").ToString();
            lblAdminCategoryHeader.Text = GetLocalResourceObject("lblAdminCategoryHeaderText").ToString();
            lblCategoryList.Text = GetLocalResourceObject("lblCategoryListText").ToString();
            lblCategoryName.Text = GetLocalResourceObject("lblCategoryNameText").ToString();
            lblLocalizedCategoryName.Text = GetLocalResourceObject("lblLocalizedCategoryNameText").ToString();

            btnAddCategory.Text = GetLocalResourceObject("btnAddCategoryText").ToString();

            string validateCategoryNameRequired = GetLocalResourceObject("rfvalCategoryNameText").ToString();
            rfvalCategoryName.ToolTip = validateCategoryNameRequired;
            rfvalCategoryName.ErrorMessage = validateCategoryNameRequired;

            string validateLocCategoryNameRequired = GetLocalResourceObject("rfvalLocalizedCategoryNameText").ToString();
            rfvalLocalizedCategoryName.ToolTip = validateLocCategoryNameRequired;
            rfvalLocalizedCategoryName.ErrorMessage = validateLocCategoryNameRequired;

            string validateCategoryNameUsed = GetLocalResourceObject("cusvalCategoryNameText").ToString();
            cusvalCategoryName.ToolTip = validateCategoryNameUsed;
            cusvalCategoryName.ErrorMessage = validateCategoryNameUsed;

            string validateLocCategoryNameUsed = GetLocalResourceObject("cusvalLocalizedCategoryNameText").ToString();
            cusvalLocalizedCategoryName.ToolTip = validateLocCategoryNameUsed;
            cusvalLocalizedCategoryName.ErrorMessage = validateLocCategoryNameUsed;

            valsumCreateCategory.HeaderText = GetLocalResourceObject("valsumCreateCategoryText").ToString();
        }
    }
}